package com.ruoyi.quartz.task;

import com.alibaba.fastjson2.JSON;
import com.aliyun.teautil.Common;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.quartz.dto.VDTO;
import com.ruoyi.quartz.gs.Content;
import com.ruoyi.quartz.gs.RootObject;
import com.ruoyi.system.domain.UserOssTask;
import com.ruoyi.system.domain.UserTask;
import com.ruoyi.system.mapper.UserTaskMapper;
import com.ruoyi.system.service.IUserFundsService;
import com.ruoyi.system.service.IUserOssTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.aliyun.com.viapi.FileUtils;
import com.aliyun.tea.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.aliyun.videoenhan20200320.Client;
import com.aliyun.videoenhan20200320.models.GetAsyncJobResultRequest;
import com.aliyun.videoenhan20200320.models.GetAsyncJobResultResponse;
import com.aliyun.videoenhan20200320.models.MergeVideoFaceRequest;
import com.aliyun.videoenhan20200320.models.MergeVideoFaceResponse;
import com.aliyuncs.exceptions.ClientException;

import java.io.IOException;
import java.util.UUID;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component("ryTask")
public class RyTask {
    @Autowired
    private UserTaskMapper userTaskMapper;
    @Autowired
    private IUserFundsService iUserFundsService;
    @Autowired
    private IUserOssTaskService iUserOssTaskService;

    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params) {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams() {
        System.out.println("执行无参方法");
    }


    public void selectUserTaskList() throws Exception {
        List<UserTask> userTaskList = userTaskMapper.selectUserTaskListByComplete();
        if (userTaskList.size() > 0) {
            ArrayList<String> idWorks = new ArrayList<>();
            ArrayList<String> idProjects = new ArrayList<>();
            for (UserTask userTask : userTaskList) {
                if (!("").equals(userTask.getIdProject())) {
                    idProjects.add(userTask.getIdProject());
                    System.out.println(userTask);
                }
                if (!("").equals(userTask.getIdWorks()) && !userTask.getIdWorks().equals("0")) {
                    idWorks.add(userTask.getIdWorks());
                }
            }
            if (idWorks.size() > 0 || idProjects.size() > 0) {
                GsTask gsTask = new GsTask();
                RootObject rootObject = gsTask.Progress(idProjects.toString(), idWorks.toString());
                for (Content content : rootObject.getBody().getContent()) {
                    UserTask userTask = new UserTask();
                    UserTask ul = userTaskMapper.selectUserTaskByTaskId(content.getIdProject());
                    BeanUtils.copyProperties(ul, userTask);
                    userTask.setName(content.getIdProject()+".mp4");
                    if ("-1".equals(content.getProcessStatus())) {
                        userTask.setProcessProgress("0%");
                    } else if ("0".equals(content.getProcessStatus())) {
                        if (content.getProcessProgress() > 0 && (content.getProcessProgress() - 20) < 0) {
                            userTask.setProcessProgress("0%");
                        }
                        if (content.getProcessProgress() > 20) {
                            userTask.setProcessProgress((content.getProcessProgress() - 20) + "%");
                        }
                    } else if ("1".equals(content.getProcessStatus())) {
                        if (!"".equals(content.getCoverUrl())) {
                            userTask.setCoverUrl(content.getCoverUrl());
                        }
                        if (!"".equals(content.getPaidPoint())) {
                            userTask.setPaidPoint(content.getPaidPoint());
                        }
                        if (!"".equals(content.getVideoUrl()) && null != content.getVideoUrl()) {
                            userTask.setTranslateVideoUrl(content.getVideoUrl());
                            userTask.setProcessProgress("80%");
                            userTask.setTask("1");
                        }
                    } else if ("-2".equals(content.getProcessStatus())){
                        if (content.getProcessProgress() > 0 && (content.getProcessProgress() - 20) < 0) {
                            userTask.setProcessProgress("0%");
                        }
                        if (content.getProcessProgress() > 20) {
                            userTask.setProcessProgress((content.getProcessProgress() - 20) + "%");
                        }
                    }
                    userTaskMapper.updateUserTask(userTask);
                }
            }
        }
        //创建阿里任务
        List<UserTask> list = userTaskMapper.selectUserTaskListByCreateAli();
        if (list.size() > 0) {
            for (UserTask userTask : list) {
                //创建阿里任务
                try {
                    MergeVideoFaceResponse res = create(userTask.getModelImg(), userTask.getTranslateVideoUrl());
                    if (200 == res.getStatusCode()) {
                        userTask.setJobid(res.getBody().getRequestId());
                        userTaskMapper.updateUserTask(userTask);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        //检查任务执行并更新状态
        List<UserTask> Transplant = userTaskMapper.selectUserTaskListByTransplant();
        if (Transplant.size() > 0) {
            for (UserTask userTask : Transplant) {
                GetAsyncJobResultResponse getAsyncJobResultResponse = getWork(userTask.getJobid());
                if ("PROCESS_SUCCESS".equals(getAsyncJobResultResponse.getBody().getData().getStatus())) {
                    VDTO vdto = JSON.parseObject(getAsyncJobResultResponse.getBody().getData().getResult(), VDTO.class);
                    String videoUrl = vdto.getVideoUrl();
                    if (videoUrl.contains("http://")){
                        videoUrl = videoUrl.replace("http://","https://");
                    }
                    userTask.setVideoUrl(videoUrl);
                    userTask.setProcessProgress("100%");
                    userTask.setTask("2");
                    userTask.setUpdateTime(new Date());
                    userTask.setQiniuStart("0");
                    //计入用户消费信息。
                    iUserFundsService.updateUserFundsByTask(userTask);
                    //阿里云OSS存储
//                    AddOSS(userTask);
                }
                userTaskMapper.updateUserTask(userTask);
            }
        }
    }

    public static Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        Config config = new Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId("LTAI5tLEqDgixECTnRbXzTS1")
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret("EVafnha5xj5o5wYxPxQYS3YKyLXjBg");
        // Endpoint 请参考 https://api.aliyun.com/product/videoenhan
        config.endpoint = "videoenhan.cn-shanghai.aliyuncs.com";
        return new com.aliyun.videoenhan20200320.Client(config);
    }

    public static MergeVideoFaceResponse create(String imgurl, String videourl) throws Exception {
        Client client = createClient();
        MergeVideoFaceRequest mergeVideoFaceRequest = new MergeVideoFaceRequest().setVideoURL(alioss(videourl)).setReferenceURL(alioss(imgurl)).setAddWatermark(false).setEnhance(false);
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            MergeVideoFaceResponse resp = client.mergeVideoFaceWithOptions(mergeVideoFaceRequest, runtime);
            return resp;
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
//            System.out.println(error.getMessage());
            // 诊断地址
            Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
//            System.out.println(error.getMessage());
            // 诊断地址
//            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }

    public static String alioss(String file) throws ClientException, IOException {
        String accessKeyId = "LTAI5tLEqDgixECTnRbXzTS1";
        String accessKeySecret = "EVafnha5xj5o5wYxPxQYS3YKyLXjBg";
        // 场景一，使用本地文件
//        String file = "/tmp/bankCard.png";
        // 场景二，使用任意可访问的url
//         String file = "https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg";
        FileUtils fileUtils = FileUtils.getInstance(accessKeyId, accessKeySecret);
        return fileUtils.upload(file);
    }

    public static GetAsyncJobResultResponse getWork(String JobId) throws Exception {
        Client client = createClient();
        GetAsyncJobResultRequest getAsyncJobResultRequest = new GetAsyncJobResultRequest().setJobId(JobId);
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            GetAsyncJobResultResponse getAsyncJobResultResponse = client.getAsyncJobResultWithOptions(getAsyncJobResultRequest, runtime);
            return getAsyncJobResultResponse;
        } catch (com.aliyun.tea.TeaException teaException) {
            // 获取整体报错信息。
            System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
            // 获取单个字段。
//            System.out.println(teaException.getCode());
        }
        return null;
    }

    public void AddOSS(UserTask userTask) throws Exception {
        //根据日期和用户名生产文件名
        LocalDate currentDate = LocalDate.now();
        String folder = currentDate.getYear()+"/"+currentDate.getMonthValue()+"/"+currentDate.getDayOfMonth();
        SecurityUtils.getLoginUser();
        String savepath = folder+userTask.getName();
        FileSaveDownDto dto =new FileSaveDownDto();
        dto.setSavepath(savepath);
        dto.setDownpath(userTask.getVideoUrl());
        UserOssTask userOssTask = new UserOssTask();
        userOssTask.setOssurl("https://aivitts.oss-cn-shanghai.aliyuncs.com/"+savepath);
        userOssTask.setTaskid(userTask.getId());
        userOssTask.setVideoUrl(userTask.getVideoUrl());
        userOssTask.setCreateTime(new Date());
        userOssTask.setUpdateTime(new Date());
        userOssTask.setCreateBy(userTask.getCreateBy());
        userOssTask.setUid(Long.parseLong(userTask.getCreateBy()));
        String asyncid = UUID.randomUUID().toString();
        userOssTask.setAsyncid(asyncid);
        //设置任务为等待中
        userOssTask.setStatus("0");
        userOssTask.setRetry("0");
//        AFCCli afcCli = new AFCCli();
//        afcCli.ACAdd(dto,asyncid);
        iUserOssTaskService.insertUserOssTask(userOssTask);
    }

}
